<template>
  <create-view :loading="loading" :body-style="{ height: '100%' }">
    <flexbox direction="column" align="stretch" class="crm-create-container">
      <flexbox class="crm-create-header">
        <div style="flex: 1; font-size: 17px; color: #333">{{ title }}</div>
        <img @click="hidenView" class="close" src="@/assets/img/task_close.png" />
      </flexbox>
      <flexbox class="crm-create-flex" direction="column" align="stretch">
        <div v-show="currentPage == 1" class="crm-create-body">
          <div class="create-name">基本信息</div>
          <el-form
            ref="crmForm"
            :model="crmForm"
            label-position="top"
            class="crm-create-box"
          >
            <el-row :gutter="40">
              <el-col
                v-if="
                  !(item.data.field === 'crm_wvgjii' && (expenceShow || invoiceShow)) &&
                  ((expenceShow && ['butler'].includes(item.data.field)) ||
                  !['butler', 'performance', 'invoice_type'].includes(item.data.field) ||
                  ((refundShow || costShow) && ['performance'].includes(item.data.field)) ||
                  (invoiceShow && ['invoice_type'].includes(item.data.field)))
                "
                v-for="(item, index) in crmForm.crmFields"
                :key="item.key"
                :span="item.showblock ? 24 : 12"
              >
                <el-form-item
                  :prop="'crmFields.' + index + '.value'"
                  :rules="crmRules[item.key]"
                >
                  <div slot="label" style="display: flex; align-items: flex-start; min-height: 30px;">
                    <div
                      style="
                        margin: 5px 0;
                        font-size: 12px;
                        word-wrap: break-word;
                        word-break: break-all;
                        line-height: 1.5;
                      "
                    >
                      {{ item.data.name }}
                      <span style="color: #999">
                        {{
                          item.data.input_tips ? "（" + item.data.input_tips + "）" : ""
                        }}
                      </span>
                    </div>
                  </div>
                  <component
                    :is="item.data.form_type | typeToComponentName"
                    :value="item.value"
                    :index="index"
                    :item="item"
                    :placeholder="item.data.placeholder"
                    :radio="false"
                    @value-change="fieldValueChange"
                  >
                  </component>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div v-show="currentPage == 2" class="crm-create-body">
          <div style="padding: 0 20px; font-size: 12px">
            <el-radio v-model="examineType" :label="1">固定审批流</el-radio>
            <div class="examine-items">
              <flexbox
                class="examine-item"
                v-for="(item, index) in examineList"
                :key="index"
              >
                <div class="examine-item-name">第{{ (index + 1) | numberToZh }}级</div>
                <el-select
                  class="examine-item-select"
                  v-model="item.type"
                  @focus="selectOptionsFocus(item, index)"
                  @change="selectOptionsChange(item)"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="itemOption in item.options"
                    :key="itemOption.value"
                    :label="itemOption.name"
                    :value="itemOption.value"
                  >
                  </el-option>
                </el-select>
                <xh-user-cell
                  v-if="item.show"
                  class="examine-item-user"
                  :radio="false"
                  :index="index"
                  @value-change="flowUserSelect"
                  :value="item.value"
                >
                </xh-user-cell>
                <i
                  class="el-icon-remove examine-item-delete"
                  @click="deleteExamineItems(index)"
                ></i>
              </flexbox>
            </div>
            <div class="examine-items-add">
              <span @click="examineItemsAdd">+ 添加审批层级</span>
            </div>
            <div class="examine-add-des">
              <p>
                <span class="examine-add-required">*</span
                >当选择“负责人主管”审批时。系统仅会通知负责人主管，但负责人所有上级（主管、主管的主管）均可审批。
              </p>
              <p>
                <span class="examine-add-required">*</span
                >当选择多个“指定用户”审批时。如果指定用户没有权限查看对应的订单，系统不会通知其审批。
              </p>
              <p>
                <span class="examine-add-required">*</span
                >当选择“指定用户（任意一人）”表示指定用户中任意一人审批即可。当选择“指定用户（多人会签）”表示
                指定用户中所有人都要审批。
              </p>
            </div>
            <el-radio v-model="examineType" :label="0">授权审批人</el-radio>
          </div>
        </div>
      </flexbox>
      <div v-if="currentPage == 1" class="handle-bar">
        <el-button class="handle-button" @click.native="hidenView">取消</el-button>
        <el-button class="handle-button" type="primary" @click.native="nextPage"
          >下一页</el-button
        >
      </div>
      <div v-if="currentPage == 2" class="handle-bar">
        <el-button class="handle-button" @click.native="hidenView">取消</el-button>
        <el-button class="handle-button" type="primary" @click.native="saveField"
          >保存</el-button
        >
        <el-button class="handle-button" type="primary" @click.native="currentPage = 1"
          >上一页</el-button
        >
      </div>
    </flexbox>
  </create-view>
</template>
<script type="text/javascript">
import CreateView from "@/components/CreateView";
import {
  oaExamineCategorySave,
  oaExamineCategoryUpdate,
} from "@/api/systemManagement/workbench"; // 审批类型创建
import { getDivisionData } from "@/api/systemManagement/division";

import {
  XhInput,
  XhTextarea,
  XhSelect,
  XhMultipleSelect,
  XhUserCell,
  XhStrucUserCell,
} from "@/components/CreateCom";
import Nzhcn from "nzh/cn";

export default {
  name: "create-examine-category", // 所有新建效果的view
  components: {
    CreateView,
    XhInput,
    XhTextarea,
    XhSelect,
    XhMultipleSelect,
    XhUserCell,
    XhStrucUserCell,
  },
  computed: {
    title() {
      if (this.handle.action === "save") {
        return "新建审批流程";
      } else if (this.handle.action === "update") {
        return "编辑审批流程";
      }
    },
    expenceShow() {
      let res = false;
      if (this.crmForm.crmFields.length > 0) {
        res = this.crmForm.crmFields[0].value.includes("报销");
      }
      return res;
    },
    refundShow() {
      let res = false;
      if (this.crmForm.crmFields.length > 0) {
        res = this.crmForm.crmFields[0].value.includes("退款");
      }
      return res;
    },
    invoiceShow() {
      let res = false;
      if (this.crmForm.crmFields.length > 0) {
        res = this.crmForm.crmFields[0].value.includes("开票");
      }
      return res;
    },
    costShow() {
      let res = false;
      if (this.crmForm.crmFields.length > 0) {
        res = this.crmForm.crmFields[0].value.includes("成本");
      }
      return res;
    },
  },
  data() {
    return {
      // 标题展示名称
      loading: false,
      // 自定义字段验证规则
      crmRules: {},
      // 自定义字段信息表单
      crmForm: {
        crmFields: [],
      },
      // 总两页 当前页
      currentPage: 1,
      examineType: 1, // 1 固定 0 授权
      divisionList: [], // 事业部列表
      examineList: [
        {
          type: 1,
          value: [],
          show: false,
          options: [
            { name: "负责人主管", value: 1 },
            { name: "指定用户（任意一人）", value: 2 },
            { name: "指定用户（多人会签）", value: 3 },
            { name: "全局主管", value: 5 },
          ],
        },
      ],
    };
  },
  filters: {
    /** 根据type 找到组件 */
    typeToComponentName(form_type) {
      if (form_type == "text") {
        return "XhInput";
      } else if (form_type == "textarea") {
        return "XhTextarea";
      } else if (form_type == "select") {
        return "XhSelect";
      } else if (form_type == "structure") {
        return "XhStrucUserCell";
      } else if (form_type == "user") {
        return "XhUserCell";
      } else if (form_type == "multiple_select") {
        return "XhMultipleSelect";
      }
    },
    numberToZh: function (value) {
      return Nzhcn.encodeS(value);
    },
  },
  props: {
    handle: {
      type: Object,
      default: () => {
        return {
          type: "examineflow", // examine 审批 审批流 examineflow
          action: "save", // save 创建  update 编辑
          id: "",
          data: null, // 编辑数据
        };
      },
    },
  },
  async mounted() {
    document.body.appendChild(this.$el);
    await this.getDivisionList();
    this.getField();
    if (this.handle.data) {
      // data 存在就处理 save
      if (this.handle.data.config && this.handle.data.config === 1) {
        this.examineList = [];
        for (let index = 0; index < this.handle.data.stepList.length; index++) {
          const element = this.handle.data.stepList[index];
          var item = {};
          item["type"] = element.status;
          if (element.status === 2 || element.status === 3) {
            item["show"] = true;
            item["value"] = element.user_id_info;
          } else {
            item["show"] = false;
            item["value"] = [];
          }
          if (index === 0) {
            item["options"] = [
              { name: "负责人主管", value: 1 },
              { name: "指定用户（任意一人）", value: 2 },
              { name: "指定用户（多人会签）", value: 3 },
              { name: "全局主管", value: 5 },
            ];
          } else {
            item["options"] = [
              { name: "负责人主管", value: 1 },
              { name: "指定用户（任意一人）", value: 2 },
              { name: "指定用户（多人会签）", value: 3 },
              { name: "上一级审批人主管", value: 4 },
              { name: "全局主管", value: 5 },
            ];
          }
          this.examineList.push(item);
        }
      } else {
        this.examineType = 0;
      }
    }
  },
  methods: {
    // 获取事业部列表
    getDivisionList() {
      return new Promise((resolve) => {
        getDivisionData()
          .then((res) => {
            let list = res.data.list;
            list = list.map((item) => item.name);
            this.divisionList = list;
            resolve();
          })
          .catch(() => {
            this.divisionList = [];
            resolve();
          });
      });
    },
    // 字段的值更新
    fieldValueChange(data) {
      var item = this.crmForm.crmFields[data.index];
      item.value = data.value;
      
      // 当审批流程名称改变时，动态更新performance字段的选项
      if (item.data.field === "title") {
        this.updatePerformanceOptions(data.value);
      }
      
      //无事件的处理 后期可换成input实现
      // if (item.data.form_type == 'structure') {
      //   this.$refs.crmForm.validateField('crmFields.' + data.index + '.value')
      // }
    },
    // 根据审批流程名称更新performance选项
    updatePerformanceOptions(titleValue) {
      const performanceField = this.crmForm.crmFields.find(field => field.data.field === "performance");
      if (performanceField) {
        const newOptions = this.getPerformanceOptions(titleValue);
        performanceField.data.setting = newOptions;
        // 如果当前值不在新选项中，重置为"全部"
        if (!newOptions.includes(performanceField.value)) {
          performanceField.value = "全部";
        }
      }
    },
    // 获取自定义字段
    getField() {
      var field = [];
      // 如果是审批添加 加入审批相关信息
      field.push({
        field: "title",
        form_type: "text",
        is_null: 1,
        name: "审批流程名称",
        setting: [],
        input_tips: "",
        value: this.handle.data ? this.handle.data.title : "",
      });
      field.push({
        field: "structure",
        form_type: "structure",
        is_null: 0,
        name: "可视范围",
        setting: [],
        input_tips: "默认全公司",
        value: {
          users: this.handle.data ? this.handle.data.user_ids_info : [],
          strucs: this.handle.data ? this.handle.data.structure_ids_info : [],
        },
      });
      field.push({
        field: "department",
        form_type: "select",
        is_null: 1,
        name: "事业部",
        setting: this.divisionList,
        input_tips: "",
        value: this.handle.data ? this.handle.data.department : "全部",
      });
      field.push({
        field: "money",
        form_type: "text",
        is_null: 1,
        name: "最低金额",
        setting: [],
        input_tips: "",
        value: this.handle.data ? this.handle.data.money : 0,
      });
      field.push({
        field: "butler",
        form_type: "select",
        is_null: 1,
        name: "人员限制",
        setting: ["全部", "管家", "非管家"],
        input_tips: "",
        value: this.handle.data ? this.handle.data.butler : "全部",
      });
      field.push({
        field: "crm_wvgjii",
        form_type: "multiple_select",
        is_null: 1,
        name: "订单类型",
        setting: ["常规", "记账", "特批", "转换常规", "转换记账"],
        input_tips: "",
        value: this.handle.data ? this.handle.data.crm_wvgjii ? this.handle.data.crm_wvgjii.split(',') : [] : [],
      });
      field.push({
        field: "notice_user_id",
        form_type: "user",
        is_null: 0,
        name: "抄送人",
        setting: [],
        input_tips: "",
        placeholder: "选择抄送人",
        value: [],
      });
      field.push({
        field: "performance",
        form_type: "select",
        is_null: 1,
        name: "业绩处理方式",
        setting: this.getPerformanceOptions(this.handle.data ? this.handle.data.title : ""),
        input_tips: "",
        value: this.handle.data ? this.handle.data.performance : "全部",
      });
      field.push({
        field: "type",
        form_type: "select",
        is_null: 1,
        name: "审批类型",
        setting: ["退款", "报销", "开票", "成本调整", "应收款调整"],
        input_tips: "",
        value: this.handle.data ? this.handle.data.type : "",
      });
      field.push({
        field: "invoice_type",
        form_type: "select",
        is_null: 1,
        name: "开票类型",
        setting: ["全部", "正常开票", "先票后款"],
        input_tips: "",
        value: this.handle.data ? this.handle.data.invoice_type : "全部",
      });
      field.push({
        field: "remark",
        form_type: "textarea",
        is_null: 0,
        name: "审批流程说明",
        setting: [],
        input_tips: "",
        value: this.handle.data ? this.handle.data.remark : "",
      });
      this.getcrmRulesAndModel(field);
    },
    // 根据审批流程名称获取performance选项
    getPerformanceOptions(titleValue) {
      let res = ["全部"];
      // 优先使用传入的titleValue，否则使用handle.data中的title，最后尝试从表单中获取
      let title = titleValue;
      if (!title && this.handle.data && this.handle.data.title) {
        title = this.handle.data.title;
      }
      if (!title && this.crmForm.crmFields.length > 0) {
        const titleField = this.crmForm.crmFields.find(field => field.data.field === "title");
        if (titleField) {
          title = titleField.value;
        }
      }
      
      if (title) {
        if (title.includes("成本")) {
          res.push("核定成本调整（提成退回）");
          res.push("核定成本调整（业绩抵扣）");
        } else if (title.includes("退款")) {
          res.push("退款申请（提成退回）");
          res.push("退款申请（业绩抵扣）");
        }
      }
      return res;
    },
    // 根据自定义字段获取自定义字段规则
    getcrmRulesAndModel(list) {
      for (let index = 0; index < list.length; index++) {
        const item = list[index];
        /** 规则数据 */
        var tempList = [];

        //验证必填
        if (item.is_null == 1) {
          tempList.push({
            required: true,
            message: item.name + "不能为空",
            trigger: ["blur", "change"],
          });
        }

        this.crmRules[item.field] = tempList;

        /** 表单数据 */
        var params = {};
        params["value"] = item.value;
        params["key"] = item.field;
        params["data"] = item;
        if (item.form_type == "textarea") {
          params["showblock"] = true; // 展示整行效果
        }
        this.crmForm.crmFields.push(params);
      }
    },
    // 保存数据
    saveField() {
      this.$refs.crmForm.validate((valid) => {
        if (valid) {
          if (this.validStepsInfo()) {
            this.submiteParams(this.crmForm.crmFields);
          }
        } else {
          this.$message.error("请完善必填信息");
          return false;
        }
      });
    },
    validStepsInfo() {
      for (let index = 0; index < this.examineList.length; index++) {
        const element = this.examineList[index];
        if ((element.type === 2 || element.type === 3) && element.value.length === 0) {
          this.$message.error("请添加员工");
          return false;
        }
      }
      return true;
    },
    /** 上传 */
    submiteParams(array) {
      this.loading = true;
      var params = this.getSubmiteParams(array);
      if (this.handle.action == "update") {
        params.id = this.handle.id;
      }
      if (!this.expenceShow) {
        delete params.butler;
      }
      if (!this.refundShow && !this.costShow) {
        delete params.performance;
      }
      if (!this.invoiceShow) {
        delete params.invoice_type;
      }
      this.getRequest()(params)
        .then((res) => {
          this.loading = false;
          // 回到保存成功
          this.$emit("save");
          if (this.handle.action == "save") {
            // 如果是新建 提示去创建表单
            this.$confirm("您将继续完成审批表单的创建", "创建成功", {
              showCancelButton: false,
              confirmButtonText: "确定",
              type: "warning",
            })
              .then(() => {
                this.hidenView();
                this.$router.push({
                  name: "handlefield",
                  params: {
                    type: "oa_examine",
                    id: res.data.category_id,
                  },
                });
              })
              .catch(() => {});
          } else {
            this.$message.success(res.data);
            this.hidenView();
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 请求url
    getRequest() {
      return this.handle.action === "update"
        ? oaExamineCategoryUpdate
        : oaExamineCategorySave;
    },
    // 请求参数
    getSubmiteParams(array) {
      var params = {};
      for (let index = 0; index < array.length; index++) {
        const element = array[index];
        // 关联产品数据需要特殊拼接
        if (element.key === "structure") {
          params["user_ids"] = element.value["users"].map(function (item) {
            return item.id;
          });
          params["structure_ids"] = element.value["strucs"].map(function (item) {
            return item.id;
          });
        } else if (element.key === "notice_user_id") {
          // 抄送人字段，只提取用户ID数组
          params[element.key] = element.value.map(function (item) {
            return item.id;
          });
        } else {
          params[element.key] = element.value;
        }
      }

      var steps = [];
      for (let index = 0; index < this.examineList.length; index++) {
        const element = this.examineList[index];
        steps.push({
          status: element.type,
          user_id: element.value.map(function (item) {
            return item.id;
          }),
        });
      }
      params["config"] = this.examineType;
      params["step"] = steps;
      return params;
    },
    // 下一页
    nextPage() {
      this.$refs.crmForm.validate((valid) => {
        if (valid) {
          this.currentPage = 2;
        }
      });
    },
    selectOptionsChange(item) {
      if (item.type == 2 || item.type == 3) {
        item.show = true;
      } else {
        item.show = false;
      }
    },
    selectOptionsFocus(item, index) {
      if (this.examineList.length > 1) {
        var lastItem = index > 0 ? this.examineList[index - 1] : null;
        var nextItem = null;
        if (index < this.examineList.length - 1) {
          var nextItem = this.examineList[index + 1];
        }

        var removeTwo = false;
        var removeThree = false;
        var removeFour = false;

        // 任一 会签 的下面不能是 上一级
        if (lastItem && (lastItem.type === 2 || lastItem.type === 3)) {
          removeFour = true;
        }

        // 上一级 的上面不能是 会签 任一
        if (nextItem && nextItem.type === 4) {
          removeTwo = true;
          removeThree = true;
        }

        var options = [{ name: "负责人主管", value: 1 }];

        if (!removeTwo) {
          options.push({ name: "指定用户（任意一人）", value: 2 });
        }
        if (!removeThree) {
          options.push({ name: "指定用户（多人会签）", value: 3 });
        }
        if (!removeFour) {
          options.push({ name: "上一级审批人主管", value: 4 });
        }
        options.push({ name: "全局主管", value: 5 });
        item.options = options;
      }
    },
    examineItemsAdd() {
      this.examineList.push({
        type: 1,
        value: [],
        show: false,
        options: [
          { name: "负责人主管", value: 1 },
          { name: "指定用户（任意一人）", value: 2 },
          { name: "指定用户（多人会签）", value: 3 },
          { name: "上一级审批人主管", value: 4 },
          { name: "全局主管", value: 5 },
        ],
      });
    },
    // 类型选择
    flowUserSelect(data) {
      var item = this.examineList[data.index];
      item.value = data.value;
    },
    deleteExamineItems(index) {
      this.examineList.splice(index, 1);
    },
    hidenView() {
      this.$emit("hiden-view");
    },
  },
  destroyed() {
    // remove DOM node after destroy
    if (this.$el && this.$el.parentNode) {
      this.$el.parentNode.removeChild(this.$el);
    }
  }
};
</script>
<style lang="scss" scoped>
.crm-create-container {
  position: relative;
  height: 100%;
}

.crm-create-flex {
  position: relative;
  overflow-x: hidden;
  overflow-y: auto;
  flex: 1;
}

.crm-create-header {
  height: 40px;
  margin-bottom: 20px;
  padding: 0 10px;
  flex-shrink: 0;
  .close {
    display: block;
    width: 40px;
    height: 40px;
    margin-right: -10px;
    padding: 10px;
  }
}
.create-name {
  font-size: 12px;
  padding: 0 10px;
  margin-left: 15px;
  margin-bottom: 10px;
  color: #333333;
  border-left: 2px solid #46cdcf;
}

.crm-create-body {
  flex: 1;
  overflow-x: hidden;
  overflow-y: auto;
}

/** 将其改变为flex布局 */
.crm-create-box {
  display: flex;
  flex-wrap: wrap;
  padding: 0 20px;
}

.el-form-item /deep/ .el-form-item__label {
  line-height: normal;
  font-size: 13px;
  color: #333333;
  position: relative;
  padding-left: 8px;
  padding-bottom: 0;
  min-height: 30px;
}

.el-form /deep/ .el-form-item {
  margin-bottom: 0px;
  min-height: 90px;
  display: flex;
  flex-direction: column;
}

.el-form /deep/ .el-form-item.is-required .el-form-item__label:before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
  position: absolute;
  left: 0;
  top: 5px;
}

.examine-items {
  padding: 10px 0;
}

.examine-item {
  padding-bottom: 8px;
  .examine-item-name {
    width: 60px;
    padding-left: 20px;
    font-size: 13px;
    margin-right: 20px;
  }
  .examine-item-select {
    margin-right: 20px;
  }
  .examine-item-user {
    flex: 1;
    margin-right: 42px;
  }
  .examine-item-delete {
    color: #ff6767;
    font-size: 22px;
    margin: 0 10px;
    display: none;
  }
}

.examine-item:hover {
  .examine-item-delete {
    display: block;
  }
  .examine-item-user {
    margin-right: 0px;
  }
}

.examine-items-add {
  padding: 5px 0 20px 0;
  font-size: 13px;
  color: $xr-color-primary;
}

.examine-add-des {
  font-size: 12px;
  background-color: #fffcf0;
  padding: 10px;
  line-height: 23px;
  color: #999;
  margin-bottom: 10px;
  .examine-add-required {
    color: #ff6767;
  }
}
.handle-bar {
  position: relative;
  .handle-button {
    float: right;
    margin-top: 5px;
    margin-right: 20px;
  }
}
</style>
